package com.java.socket.tcp.singleclient.client;

import java.io.*;
import java.net.Socket;

/**
 * 单线程客户端Socket
 *
 * @author xzmeasy
 * @version 1.0
 * @since 星期一 十二月,2018
 */
@SuppressWarnings("Duplicates")
public class ClientSocketExample {

    public static void main(String[] args) {
        // 创建Socket对象
        try {
            Socket socket = new Socket("localhost", 8888);

            // 从Socket创建输出流，用于向服务段发送消息
            OutputStream outputStream = socket.getOutputStream();
            // 将字节流转换成字符流, 提高写效率
            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            // 向服务端发送消息
            PrintWriter printWriter = new PrintWriter(writer);
            String message = "客户端发送的消息...";
            printWriter.write(message);
            printWriter.flush();
            socket.shutdownOutput();


            // 从Socket中获取输入流，用于接收服务段的反馈信息
            InputStream inputStream = socket.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String temp = null;
            StringBuffer info = new StringBuffer();
            while ((temp = reader.readLine()) != null) {
                info.append(temp);
            }
            System.out.println("服务端的反馈信息: " + info.toString());

            // 关闭资源
            reader.close();
            inputStreamReader.close();
            inputStream.close();
            printWriter.close();
            writer.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("Socket连接失败");
        }
    }

}
